﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Milan.Deploy
{
	/// <summary>
	/// Runs a threaded version of the scanner.
	/// So Start returns immediately, and we must override Run instead.
	/// We should wait on the quit event: QuitEvent
	/// </summary>
	public abstract class ThreadScanner : Scanner
	{
		public ThreadScanner(Application application) : base(application)
		{
		}
		public override bool OnStart(string[] m_args)
		{
			m_thread.Start(this);
			m_isRunning.WaitOne();
			return true;	// We started ok
		}
		public override void OnStop()
		{
			m_quitEvent.Set();
			m_thread.Join();
		}
		private Thread m_thread = new Thread(RunStatic);
		private ManualResetEvent m_quitEvent = new ManualResetEvent(false);
		protected ManualResetEvent QuitEvent
		{
			get
			{
				return m_quitEvent;
			}
		}
		private ManualResetEvent m_isRunning = new ManualResetEvent(false);
		protected ManualResetEvent IsRunningEvent
		{
			get
			{
				return m_isRunning;
			}
		}
		private static void RunStatic(object param)
		{
			((ThreadScanner)param).m_isRunning.Set();
			((ThreadScanner)param).Run();
			((ThreadScanner)param).m_isRunning.Reset();
		}
		protected abstract void Run();
	}
}
